//app.js
var util = require("./utils/util");
var util_md5 = require("./utils/md5");
App({
  globalData: {
    md5secret: "c4fc9067d07349da83c4536db33b90t5", //md5加密秘钥
    gedanData: "", //跳转到歌单详情传的数据
    userData: "", //用户信息
    encryptedData: "",
    iv: "",
    signature: "",
    rawData: "",
    countryData: "", //登录选择的国家区号数据
    uid: "a2c9eb48-8eb2-3714-b58d-3b31910d2bbb",
    token: "",
    appId: "wx2997edb0976a513a", //小程序appid
    secret: "56028ad9843dd7cc9dcafefb2fdd00de", //小程序secret
    canConnect: false,
    isFullSucreen: false, // 当前设备是否为 FullSucreen
    websocket_object: {}, //websocket实例
    websocket_status: false, //websocket连接状态
    singerImg: "",
    nowSongName: "",
    nowSingerName: "",
    volume_val: "",
    mic_volume_val: "",
    timeout: 50000,
    timeoutObj: null,
    selectImgList: [], //意见反馈图片list
    selectVideoList: [], //意见反馈视频list
    selectMediaList: [],
    uploadPercent: "", //上传百分比
  },

  onLaunch: function () {
    // 判断是否是全面屏手机
    this.checkFullSucreen();
    // 展示本地存储能力

    // 获取用户信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting["scope.userInfo"]) {
          wx.getUserInfo({
            success: (res) => {
              console.log("个人信息", res);
              wx.setStorageSync("wxImg", res.userInfo.avatarUrl);
              wx.setStorageSync("wxName", res.userInfo.nickName);
              this.globalData.userInfo = res.userInfo;

              // if (this.userInfoReadyCallback) {
              //   this.userInfoReadyCallback(res);
              // }
            },
          });
        }
      },
    });
  },
  onShow: function (options) {
    var that = this;
    wx.checkSession({
      success() {
        //session_key 未过期，并且在本生命周期一直有效
        that.getToken(function (res) {
          // console.log(res.data, "token数据");
          wx.setStorage({
            key: "token",
            data: res.data,
          });
          that.globalData.token = res.data;
          that.websocket_connect();
        });
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        that.getToken(function (res) {
          // console.log(res.data, "token数据");
          wx.setStorage({
            key: "token",
            data: res.data,
          });
          that.globalData.token = res.data;
          that.websocket_connect();
        });
      },
    });
  },
  // 重置定时器心跳
  reset: function () {
    var that = this;
    // console.log('重置定时器心跳')
    clearTimeout(this.timeoutObj);
    that.start();
  },
  // 定时器开始
  start: function () {
    var that = this;
    // console.log('定时器开始')
    that.globalData.timeoutObj = setTimeout(function () {
      that.globalData.websocket_object.send({
        data: "ping",
        success: function (res) {
          // console.log("心跳发送成功", res);
        },
      });
    }, that.globalData.timeout);
  },

  /**
   * @description: 获取token
   * @param        {Function} callback     [description]  回调函数
   */

  getToken: function (callback) {
    // 登录
    wx.login({
      success: (res) => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log(res.code, "code码");
        // 用户登录凭证
        var u_code = res.code;
        // 设备的uid
        var u_id = this.globalData.uid;
        // var u_id="ab421999-2e93-3dae-b3ef-39a014778d20"

        // 初始化获取时间戳
        var u_timestamp = new Date().getTime();
        var u_verify =
          this.globalData.md5secret +
          "code=" +
          u_code +
          "&timestamp=" +
          u_timestamp;
        // console.log(u_verify, "未加密的签名");
        // 生成签名
        var signature = util_md5.hexMD5(u_verify);
        // console.log(signature, "加密后的签名");
        wx.request({
          url:
            util.api +
            "/wechat/connect?code=" +
            u_code +
            "&uid=" +
            u_id +
            "&timestamp=" +
            u_timestamp +
            "&signature=" +
            signature,
          data: {},
          method: "GET",
          header: {
            "content-type": "application/x-www-form-urlencoded",
          },
          success: function (res) {
            callback(res.data);
          },
        });
      },
    });
  },
  // 用来测试h5登录
  getToken1: function (callback) {
    // 登录
    wx.login({
      success: (res) => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res.code, "code码");
        // 用户登录凭证
        var u_code = res.code;
        // 设备的uid
        var u_id = "a2c9eb48-8eb2-3714-b58d-3b31910d2bbb";
        // var u_id="ab421999-2e93-3dae-b3ef-39a014778d20"

        // 初始化获取时间戳
        var u_timestamp = new Date().getTime();
        var u_verify =
          this.globalData.md5secret +
          "timestamp=" +
          u_timestamp +
          "&uid=" +
          u_id;
        console.log(u_verify, "未加密的签名");
        // 生成签名
        var signature = util_md5.hexMD5(u_verify);
        console.log(signature, "加密后的签名");
      },
    });
  },
  // 检测是否是全面屏手机
  checkFullSucreen: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res, "屏幕尺寸"); // 根据 屏幕高度 进行判断

        if (res.screenHeight - res.safeArea.height > 40) {
          console.log("全面屏");
          that.globalData.isFullSucreen = true;
        }
      },
    });
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType;
        console.log("网络状况", networkType);
      },
    });
  },
  // websocket连接
  websocket_connect() {
    // console.log(util.socketapi);
    var that = this;
    var u_id = that.globalData.uid;
    var u_timestamp = new Date().getTime();
    // console.log("时间戳", u_timestamp);
    var u_verify =
      that.globalData.md5secret + "timestamp=" + u_timestamp + "&uid=" + u_id;
    // console.log("未加密的签名", u_verify);
    // 生成签名
    var signature = util_md5.hexMD5(u_verify);
    // console.log("加密后的签名", signature);
    that.globalData.websocket_object = wx.connectSocket({
      url:
        util.socketapi +
        "/connection.ws?uid=" +
        u_id +
        "&timestamp=" +
        u_timestamp +
        "&signature=" +
        signature,
      header: {
        "content-type": "application/x-www-form-urlencoded",
        Authorization: "Bearer " + that.globalData.token,
      },
      success: function (res) {
        // console.log("连接成功", res);
        that.globalData.websocket_status = true;
      },
    });
    that.globalData.websocket_object.onMessage(function (res) {
      that.reset();
      // console.log("接收", JSON.parse(res.data));
      let receive_data = JSON.parse(res.data);
      let event_type = receive_data.data.event;
      if (event_type == "song_play") {
        that.globalData.singerImg = receive_data.data.song.singerImg;
        that.globalData.nowSongName = receive_data.data.song.songName;
        that.globalData.nowSingerName = receive_data.data.song.singerName;
      } else if (event_type == "mic_volume") {
        that.globalData.mic_volume_val = receive_data.data.val;
      } else if (event_type == "volume") {
        that.globalData.volume_val = receive_data.data.val;
      }
    });
    that.globalData.websocket_object.onClose(function (res) {
      console.log("socket断开事件", res);
      that.websocket_connect();
    });
    that.globalData.websocket_object.onError(function (res) {
      console.log("socket错误事件", res);
      that.websocket_connect();
    });
    that.globalData.websocket_object.onOpen(function (res) {
      console.log("socket打开事件", res);
      that.start();
    });
  },
});
